package com.nowcoder.community.service;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.util.SensitiveFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 当前业务简单，没有注释，详细信息查看mapper中注释即可
 * @author ：LY
 * @date ：Created in 2021/1/18 21:54
 * @modified By：
 */
@Service
public class DiscussPostSerivce {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostSerivce.class);
    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;
    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    //caffeine的核心接口Cache，LoadingCache,AsyncLoadingCache

    //帖子列表的缓存
    private LoadingCache<String,List<DiscussPost>> postListCache;

    //缓存帖子总数
    private LoadingCache<Integer,Integer> postRowsCache;

    @PostConstruct
    public void  init(){
        //初始化帖子列表缓存
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(key -> {
                    if (key == null || key.length() ==0){
                        throw new IllegalArgumentException("缓存参数错误");

                    }
                        String[] params = key.split(":");
                        if (params == null || params.length !=2){
                            throw new IllegalArgumentException("缓存参数错误");
                        }
                        int offset = Integer.valueOf(params[0]);
                        int limit =Integer.valueOf(params[1]);

                        //二级缓存位置  Redis >mysql

                    logger.debug("load post list from DB");
                    return discussPostMapper.selectDiscussPosts(0,offset,limit,1);
                });
        //初始化帖子总数缓存
        postRowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds,TimeUnit.SECONDS)
                .build(key->{
                    logger.debug("load post list from DB");
                    return discussPostMapper.selectDiscussPostRows(key);
                });
        
    }

    public List<DiscussPost> findDiscussPosts(int userId,int offset,int limit,int ordermode){
        if (userId == 0 && ordermode == 1){
            return postListCache.get(offset + ":" + limit);
        }
        logger.debug("load post list from DB");
        return discussPostMapper.selectDiscussPosts(userId, offset, limit,ordermode);
    }

    public int findDiscussPostRows(int userId){
        if (userId == 0){
            return postRowsCache.get(userId);
        }
        logger.debug("load post rows from DB");
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    public int addDiscussPost(DiscussPost discussPost){

        if (discussPost == null){
            throw  new IllegalArgumentException("参数不能为空！");
        }
        discussPost.setTitle(sensitiveFilter.filter(
                HtmlUtils.htmlEscape(discussPost.getTitle())
        ));
        discussPost.setContent(sensitiveFilter.filter(
                HtmlUtils.htmlEscape(discussPost.getContent())
        ));
        return discussPostMapper.insertDiscussPost(discussPost);
    }
    public DiscussPost findDiscussPostById(int id){
        return discussPostMapper.selectDiscussPostById(id);
    }

    public int updateCommentCount(int id,int commentCount){
        return discussPostMapper.updateCommentCount(id, commentCount);
    }
    public int updateType(int id,int type){
        return discussPostMapper.updateType(id, type);
    }

    public int updateStatus(int id,int status){
        return discussPostMapper.updateStatus(id, status);
    }

    public int updateScore(int id,double score){
        return discussPostMapper.updateScore(id, score);
    }
}
